IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('MD3.RunPrimaryKeys'))
BEGIN
	DROP PROCEDURE MD3.RunPrimaryKeys
END
GO

CREATE Procedure MD3.RunPrimaryKeys
AS
    
BEGIN

    SET QUOTED_IDENTIFIER ON
    SET NOCOUNT ON 

	/*
		Runs all PK Constraints found in MD3.PrimaryKeys
		this is called from/in the PrimaryKeys folder, after the MD3.PrimaryKeys table is loaded

	*/

	

DECLARE 
	@SchemaName VARCHAR(256),
	@TableName VARCHAR(256) ,
	@PrimaryKeyName	SYSNAME ,    
	@KeyColumns VARCHAR(MAX) ,
    @IsClustered	BIT ,  
	@IdxFillFactor int ,
	@IsPadded BIT ,
    @FGorPartitionScheme VARCHAR(MAX),
	@CompressionSetting VARCHAR(50),
	@DropPK BIT 
	
DECLARE CurIndexes CURSOR FOR 	
	--get a list of FKs
	SELECT 
		SchemaName ,
		TableName ,
		PrimaryKeyName	 , 
		KeyColumns  ,
		IsClustered	  ,
		IdxFillFactor  ,
		IsPadded  ,
		FGorPartitionScheme ,
		CompressionSetting ,
		DropPK 
	FROM MD3.PrimaryKeys
	ORDER BY Id
OPEN CurIndexes
FETCH NEXT FROM curIndexes INTO 
	@SchemaName ,
	@TableName ,
	@PrimaryKeyName	 ,    
	@KeyColumns  ,
    @IsClustered	 ,  
	@IdxFillFactor  ,
	@IsPadded  ,
    @FGorPartitionScheme ,
	@CompressionSetting ,
	@DropPK ;

WHILE @@FETCH_STATUS = 0
BEGIN 

	EXEC MD3.CreatePrimaryKey   
		 @SchemaName	=   @SchemaName
		,@TableName	    	    =@TableName
		,@PrimaryKeyName	=@PrimaryKeyName
		,@KeyColumns       =@KeyColumns
		,@IsClustered      =@IsClustered
		,@FillFactor       =@IdxFillFactor
		,@PadIndex          =@IsPadded
		,@FileGroupOrPartition    =  @FGorPartitionScheme  
		,@DropPK		=@DropPK
		,@DataCompressionType=@CompressionSetting
	;

	
	
	FETCH NEXT FROM curIndexes INTO 
		@SchemaName ,
		@TableName ,
		@PrimaryKeyName	 ,    
		@KeyColumns  ,
		@IsClustered	 ,  
		@IdxFillFactor  ,
		@IsPadded  ,
		@FGorPartitionScheme ,
		@CompressionSetting ,
		@DropPK ;		
END

CLOSE curIndexes
DEALLOCATE curIndexes



END
GO
